package com.example.demo.bl;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

import com.example.demo.utils.Analyzer;
import com.example.demo.vo.SaveVO;

import org.springframework.stereotype.Service;

@Service
public class ApiService {
    public Object analyseAndGetResult(String in) {
        String path = "src\\main\\resources\\static\\" + String.valueOf(System.currentTimeMillis()) + ".txt";
        try {
            File file = new File(path);
            Writer writer = new FileWriter(file);
            writer.write(in);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        Analyzer analyzer = new Analyzer(path);
        if (!analyzer.isSuccess()) return null;
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return analyzer.getResultVO().getData();
    }


    public boolean saveFile(SaveVO in){

        try {
            String path = "src\\main\\resources\\data\\" + String.valueOf(System.currentTimeMillis());
            File txt = new File(path + ".txt");
            Writer txtWriter = new FileWriter(txt);
            txtWriter.write(in.getIn());
            txtWriter.flush();
            txtWriter.close();

            File json = new File(path + ".json");
            Writer jsonWriter = new FileWriter(json);
            jsonWriter.write(in.getJson());
            jsonWriter.flush();
            jsonWriter.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
